<?php

namespace zhtfrontend\controllers;

use common\models\datas\Type;
use zhtfrontend\components\bases\BaseController;
use zhtfrontend\components\helpers\Funs;
use zhtfrontend\models\datas\GoodsGroup;
use yii\web\BadRequestHttpException;
use yii\helpers\Json;
use yii\web\Response;
use zhtfrontend\models\datas\Goods;
use common\models\datas\Cate;
use yii\data\Pagination;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\GoodsAttr;
use yii\widgets\ActiveForm;
use common\models\datas\CateAttr;
use common\components\helpers\Tree;
use common\models\datas\TypeBrand;
use common\models\datas\Brand;
use yii\helpers\ArrayHelper;
use zhtfrontend\models\datas\Mechanic;
use yii\web\NotFoundHttpException;

class GoodsgroupController extends BaseController
{

    public function actionIndex()
    {
        $tree = $this->getCategory(5);
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = !empty($param['pageSize']) ? $param['pageSize'] : 12;
        $goods = Goods::find()->where(['type_id' => 5, 'is_delete' => 0]);
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            if (!empty($search_data['goods_name'])) {
                $goods->andWhere(['like', 'name', $search_data['goods_name']]);
            }
            if (!empty($search_data['cate_name'])) {
                $cateids = [$search_data['cate_name']];
                $cate = Cate::findOne($search_data['cate_name']);
                if ($cate->parent_id == 0) {
                    $cates = Cate::find()->where(['parent_id' => $search_data['cate_name']])->column();
                }
                $cateids = array_merge($cates, $cateids);
                $cate = Cate::find()->select('id')->Where(['in', 'id', $cateids])->column();
                $goods->andWhere(['in', 'cat_id', $cate]);
            }
        }
        $pages = new Pagination(['totalCount' => $goods->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $goods->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($model, ['cate_name', 'mechanic_name', 'brand_name', 'operate']);

        return $this->render('index', ['tree' => $tree,'data'=>$array,'pages'=>$pages]);
    }

    public function getCategory($type_id)
    {
        $site_id = Fun::getSiteId();
        $cate_attr = CateAttr::find()->select(['cat_id'])->where(['or', ['mobile_is_show' => 1], ['pc_is_show' => 1]])->andWhere(['site_id' => $site_id])->orderBy('pc_sort asc')->column();
        $category = Cate::find()->indexBy('id')->where(['in', 'id', $cate_attr])->andWhere(['type_id' => $type_id, 'is_delete' => 0])->asArray()->all();
        //$category = Cate::find()->indexBy('id')->where(['is_delete'=>0,'type_id'=>$type_id])->asArray()->all();
        $tree = (new Tree($category))->get_tree_select();
        return $tree;
    }

    public function actionCreate()
    {
        $type_id = 5;//5是商品中的组合商品的类型
        $model = new Goods();
        $model->scenario = 'update';
        $model->type_id = 5;
        $attribute = Funs::getAttribute($type_id);
        $site_id = Fun::getSiteId();
        //获取全部的分类
        $cate_attr = CateAttr::find()->select(['cat_id'])->where(['or', ['mobile_is_show' => 1], ['pc_is_show' => 1]])->andWhere(['site_id' => $site_id])->orderBy('pc_sort asc')->column();
        $category = Cate::find()->indexBy('id')->where(['in', 'id', $cate_attr])->andWhere(['is_delete' => 0])->asArray()->all();
        $cat_tree = (new Tree($category))->get_tree_select();
        //获取全部的品牌
        $brand_id = TypeBrand::find()->select(['brand_id'])->where(['type_id' => $type_id])->column();
        $brand = Brand::find()->where(['in', 'id', $brand_id])->all();
        $brand_tree = ArrayHelper::map($brand, 'id', 'name');
        //获取全部的机构
        $mids = Fun::getMechanicIds();
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0]);
        if ($mids) {
            $mechanicModel->andWhere(['id' => $mids]);
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        $mechanic_tree = (new Tree($mechanic))->get_tree_select();

        //$mechanic=Mechanic::find()->where(['site_id'=>$site_id])->asArray()->all();
        // $mechanic_tree = ArrayHelper::map($mechanic, 'id', 'name');
        //获取选择选择是否上架的选项
        $shelve_array = ['1' => '上架', '2' => '暂不上架'];
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            $model->sn = 'product' . time();//商品编号
            $model->site_id = Fun::getSiteId();
            $model->goods_type = 'group';
            $model->admin_id = \Yii::$app->user->id;
            $model->type_id = 5;
            $model->picture = '';
            if ($model->is_shelve == 1) {
                $model->up_at = time();
            }
            if (isset($post['Goods']['imageList']) && !empty($post['Goods']['imageList'])) {
                $imagelist = $post['Goods']['imageList'];
                $imagelist_arr = [];
                if (!empty($imagelist)) {
                    $imagelist_arr = explode('#|#', $imagelist);
                }
                if (!empty($post['Goods']['defaulturl']) && in_array($post['Goods']['defaulturl'], $imagelist_arr)) {
                    $model->picture = $post['Goods']['defaulturl'];
                } else {
                    if (count($imagelist_arr) > 0) {
                        $model->picture = $imagelist_arr[0];//上传的列表第一个作为展示的默认图
                    }
                }
            }
            if ($model->save(false)) {
                if (!empty($post['Goods']['groupIds'])) {
                    foreach ($post['data'] as $key => $val) {
                        $data_arr = explode(",", $val);
                        $goodsgroup = new GoodsGroup();
                        $goodsgroup->group_id = $key;
                        $goodsgroup->goods_id = $model->id;
                        $goodsgroup->discount_type = $data_arr[0];
                        $goodsgroup->price_reduce = $data_arr[1];
                        $goodsgroup->cost_reduce = $data_arr[2];
                        $goodsgroup->market_price_reduce = $data_arr[3];
                        $goodsgroup->save(false);
                    }
                }
                if (!empty($post['attr_value'])) {
                    $attribute = $post['attribute'];
                    foreach ($post['attr_value'] as $k => $v) {
                        if (!empty($v)) {//非空的扩展属性值进行保存
                            $attributes = new GoodsAttr(['goods_id' => $model->id, 'attribute_id' => $k, 'name' => $attribute[$k], 'value' => trim($v), 'obj_type' => 'attribute']);
                            $attributes->save(false);
                        }
                    }
                }
                return $this->redirectMessage('添加成功', Fun::url(['goodsgroup/index', 'type_id' => 5]));
            }
        }
        return $this->render('create', ['model' => $model, 'cat_tree' => $cat_tree, 'brand_tree' => $brand_tree, 'mechanic_tree' => $mechanic_tree, 'shelve_array' => $shelve_array, 'attribute' => $attribute]);
    }

    public function actionUpdate()
    {
        $type_id = 5;
        $id = \Yii::$app->request->get('id');
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '请求错误'));
        }
        $model = Goods::findOne(\Yii::$app->request->get('id'));
        $model->scenario = 'update';
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        //获取选择的商品的相关的信息
        $group_ids = GoodsGroup::find()->select('group_id')->where(['goods_id' => $id])->column();
        if (empty($group_ids)) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $site_id = Fun::getSiteId();
        $model->groupIds = implode(',', $group_ids);

        //获取全部的分类
        $cate_attr = CateAttr::find()->select(['cat_id'])->where(['or', ['mobile_is_show' => 1], ['pc_is_show' => 1]])->andWhere(['site_id' => $site_id])->orderBy('pc_sort asc')->column();
        $category = Cate::find()->indexBy('id')->where(['in', 'id', $cate_attr])->andWhere(['is_delete' => 0])->asArray()->all();
        $cat_tree = (new Tree($category))->get_tree_select();
        //获取全部的品牌
        $brand_id = TypeBrand::find()->select(['brand_id'])->where(['type_id' => $type_id])->column();
        $brand = Brand::find()->where(['in', 'id', $brand_id])->all();
        $brand_tree = ArrayHelper::map($brand, 'id', 'name');
        //获取全部的机构

        $mids = Fun::getMechanicIds();
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0]);
        if ($mids) {
            $mechanicModel->andWhere(['id' => $mids]);
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        $mechanic_tree = (new Tree($mechanic))->get_tree_select();
        // $mechanic=Mechanic::find()->where(['site_id'=>$site_id])->asArray()->all();
        // $mechanic_tree = ArrayHelper::map($mechanic, 'id', 'name');
        //获取选择选择是否上架的选项
        $shelve_array = ['0' => '下架', '1' => '上架', '2' => '暂不上架'];
        $data = [];
        $group_goods = Goods::find()->where(['id' => $group_ids])->all();
        if (empty($group_goods)) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '组合商品中的商品已经被删除'));
        }
        foreach ($group_goods as $key => $value) {
            $data[] = $value->toArray([], ['cate_name', 'mechanic_name', 'brand_name', 'discount_type', 'price_reduce', 'cost_reduce', 'market_price_reduce']);
        }
//        $default_json = json_encode($data, JSON_UNESCAPED_UNICODE);
        //保存产品的扩展属性
        $attribute = Funs::getAttribute($type_id, $id);
        $postdata = \Yii::$app->request->post();
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            if ($model->is_shelve == 1) {
                $model->up_at = time();
            } elseif ($model->is_shelve == 0) {
                $model->down_at = time();
            } else {
                $model->down_at = 0;
            }
            if (isset($post['Goods']['imageList']) && !empty($post['Goods']['imageList'])) {
                $imagelist = $post['Goods']['imageList'];
                $imagelist_arr = [];
                if (!empty($imagelist)) {
                    $imagelist_arr = explode('#|#', $imagelist);
                }
                if (!empty($post['Goods']['defaulturl']) && in_array($post['Goods']['defaulturl'], $imagelist_arr)) {
                    $model->picture = $post['Goods']['defaulturl'];
                } else {
                    if (count($imagelist_arr) > 0) {
                        $model->picture = $imagelist_arr[0];//上传的列表第一个作为展示的默认图
                    }
                }
            }
            if ($model->save(false)) {
                if (!empty($post['data']) && !empty($post['Goods']['groupIds'])) {
                    foreach ($post['data'] as $key => $val) {
                        $data_arr = explode(",", $val);
                        $group = GoodsGroup::findOne(['goods_id' => $model->id, 'group_id' => $key]);
                        if ($group == null) {
                            $goodsgroup = new GoodsGroup();
                            $goodsgroup->group_id = $key;
                            $goodsgroup->goods_id = $model->id;
                            $goodsgroup->discount_type = $data_arr[0];
                            $goodsgroup->price_reduce = $data_arr[1];
                            $goodsgroup->cost_reduce = $data_arr[2];
                            $goodsgroup->market_price_reduce = $data_arr[3];
                            $goodsgroup->save(false);
                        } else {
                            $group->discount_type = $data_arr[0];
                            $group->price_reduce = $data_arr[1];
                            $group->cost_reduce = $data_arr[2];
                            $group->market_price_reduce = $data_arr[3];
                            $group->save(false);
                        }
                    }
                    $post_group = explode(",", $post['Goods']['groupIds']);
                    foreach ($group_ids as $gid) {
                        if (!in_array($gid, $post_group)) {
                            $group = GoodsGroup::findOne(['goods_id' => $model->id, 'group_id' => $gid]);
                            $group->delete();
                        }
                    }
                }

                if (!empty($postdata['attr_value'])) {
                    foreach ($postdata['attr_value'] as $k => $v) {
                        /*
                         * 遍历获取填写的扩展属性，到库表中查该model该属性id是否已经存在了值了，如果存在了，则更新其value
                         * 如果不存在，则执行插入操作
                         */
                        $goodattr = GoodsAttr::findOne(['goods_id' => $model->id, 'attribute_id' => $k]);
                        if ($goodattr == null) {//执行插入操作
                            $goodattrnew = new GoodsAttr(['goods_id' => $model->id, 'attribute_id' => $k, 'value' => $v, 'obj_type' => 'attribute']);
                            $goodattrnew->save(false);
                        } else {//执行更新操作
                            $goodattr->value = $v;
                            $goodattr->save(false);
                        }
                    }
                }//保存完成商品的扩展属性
                return $this->redirectMessage('修改成功', Fun::url(['goodsgroup/index', 'type_id' => 5]));
            }
        }
        return $this->render('create', ['model' => $model, 'cat_tree' => $cat_tree, 'brand_tree' => $brand_tree, 'mechanic_tree' => $mechanic_tree, 'goodsgroup' => $data, 'shelve_array' => $shelve_array, 'attribute' => $attribute]);
    }

    public function actionAddgroup()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->isAjax) {
            if (\Yii::$app->request->post('param') != null) $param = Json::decode(\Yii::$app->request->post('param'));
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $pageSize = !empty($param['pageSize']) ? $param['pageSize'] : 12;
            $goods = Goods::find()->where(['is_delete' => 0, 'is_show' => 1, 'goods_type' => ['normal', 'gift']]);
            if (!empty($param['searchData'])) {
                $search_data = array_filter($param['searchData']);
                if (!empty($search_data['goods_name'])) {
                    $goods->andWhere(['like', 'name', $search_data['goods_name']]);
                }
            }
            $pages = new Pagination(['totalCount' => $goods->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $goods->offset($pages->offset)->limit($pages->limit)->all();
            $array = Fun::asArray($model, ['checkbox', 'cate_name', 'mechanic_name', 'brand_name', 'discount_type', 'cost_reduce', 'market_price_reduce', 'price_reduce']);
            $ajax_object = new AjaxObject();
            $ajax_object->data = $array;
            $ajax_object->pages = $pages;
            return $ajax_object;
        }
        return $this->render('addgroup');
    }

    public function actionDelete()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Goods::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->is_delete = 1;
        if ($model->save(false)) {
            return $this->redirectMessage(\Yii::t('zhtfrontend', '信息删除成功'), Fun::url(['goodsgroup/index', 'type_id' => 5]));
        }
    }

    public function actionDetails()
    {
        //$type_id=5;
        $site_id = Fun::getSiteId();
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '请求错误'));
        }
        $goods = Goods::findOne($id);
        if ($goods == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $category = null;
        $brand = null;
        $mechanic = null;

        if ($goods->cat_id != null) {
            $category = Cate::findOne($goods->cat_id);
        }
        if ($goods->brand_id != null) {
            $brand = Brand::findOne($goods->brand_id);
        }
        if ($goods->mechanic_id != null) {
            $mechanic = Mechanic::findOne(['id' => $goods->mechanic_id, 'site_id' => $site_id]);
        }
        $AttributeDetails = Funs::getExtendattributeDetails(5, $id);
        $goods_id = GoodsGroup::find()->select('group_id')->where(['goods_id' => $id])->column();
        $goodsgroup = [];
        foreach ($goods_id as $k => $v) {
            $group_goods = Goods::findOne([$v]);
            $cate = Cate::findOne($group_goods->cat_id);
            $brand_name = Brand::findOne($group_goods->brand_id);
            $mechanic_name = Mechanic::findOne($group_goods->mechanic_id);
            //$goodsgroup[$k] = Fun::asArray($group_goods, ['checkbox','cate_name','mechanic_name','brand_name']);
            $goodsgroup[$k] = [
                'id' => $v,
                'name' => $group_goods->name,
                'sn' => $group_goods->sn,
                'cate_name' => isset($cate->name) ? $cate->name : '',
                'brand_name' => isset($brand_name->name) ? $brand_name->name : '',
                'mechanic_name' => isset($mechanic_name->name) ? $mechanic_name->name : '',
                'store' => $group_goods->store,
                'price' => $group_goods->price,
                'cost' => $group_goods->cost,
                'market_price' => $group_goods->market_price,
                'is_buy' => ($group_goods->is_buy == 1) ? '可购买' : '不可购买',
                'goods_type' => $group_goods->goods_type,
            ];
        }
        return $this->render('details', ['model' => $goods, 'category' => $category, 'brand' => $brand, 'mechanic' => $mechanic, 'AttributeDetails' => $AttributeDetails, 'goodsgroup' => $goodsgroup]);
    }

    public function actionSet()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('type_id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '非法请求'));
        }
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Goods::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $form = new EasyuiForm('@app/components/forms/goodsgroupForm.php');
        //$way_a=['2'=>'会费'];
        $way_b = ['0' => '固定分成', '1' => '比例分成'];
        //根绝不同的A B模式设置不同的分成方式（A模式，只有会费这一种分成方式，B模式有固定分成和比例分成两种方式）
        $mechanic_id = Goods::find()->select('mechanic_id')->where(['id' => \Yii::$app->request->get('id')])->asArray()->one();
//        $mechanic_mode=Mechanic::find()->select('mode')->where(['id'=>$mechanic_id['mechanic_id']])->asArray()->one();
//        if(!empty($mechanic_mode)){
//            if($mechanic_mode['mode']=='a'){
//                $model->distribution_way=2;
//                $form->setItems('goods', 'distribution_way',$way_a);
//            }else{
//                $form->setItems('goods', 'distribution_way',$way_b);
//            }
//        }else{
        $form->setItems('goods', 'distribution_way', $way_b);
//        }


        $form->loadModel(['goods' => $model]);
        $form->loadDefaultValues();
        if ($form->loadData(\Yii::$app->request->post()) && $model->validate()) {
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '信息修改成功'), Fun::url(['goodsgroup/index', 'type_id' => 5]));
            }
        }
        return $this->render('set', ['form' => $form->render()]);
    }
}